import "package:ct_pa_majordomo/app.dart";
import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/api.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/check_in_info_state.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/complete/index.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/detail/index.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/due_in/index.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/widgets/info_block.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";

class CheckInDetail extends StatefulWidget {
  final int checkInId;
  final Function? changeInfo;
  const CheckInDetail({super.key, required this.checkInId, this.changeInfo});

  @override
  State<StatefulWidget> createState() => _CheckInDetailState();

}

class _CheckInDetailState extends State<CheckInDetail> {

  final List<String> tabs = ["入住详情", "完成账单", "待收账单"];
  Map _info = {"room": {}};
  Map _mainRenter = {};
  List _cohabitants = [];


  String _buildingAndRoom() {
    if (_info["room"]["buildingName"] == null && _info["room"]["name"] == null) {
      return "暂无房间信息";
    } else {
      return "${_info["room"]["buildingName"] ?? ""} ${_info["room"]["name"] ?? ""}";
    }
  }

  Future<void> _getCheckInInfo() async {
    Map resData = await checkInApi.getCheckInInfo(checkInId: widget.checkInId);
    _changeInfo(resData["data"] ?? {});
    if (widget.changeInfo != null) {
      widget.changeInfo!();
    }
  }

  void _changeInfo(Map info) {
    setState(() {
      _info = info;
      _mainRenter = _info["renterList"].firstWhere((renter) => renter["mainFlag"] == "1");
      _cohabitants = _info["renterList"].where((renter) => renter["mainFlag"] != "1").toList();
    });
  }


  @override
  void initState() {
    _getCheckInInfo();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: tabs.length,
      child: Scaffold(
        appBar: AppBar(
          title: const Text("房间详情"),
          centerTitle: true,
          backgroundColor: ThemeVars.colorPrimary,
          foregroundColor: Colors.white,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios_new),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ),
        body: NestedScrollView(
          headerSliverBuilder: (context, innerBoxIsScrolled) {
            return [
              SliverToBoxAdapter(
                child: DecoratedBox(
                  decoration: const BoxDecoration(
                    color: Colors.white,
                  ),
                  child: Column(
                    children: [
                      Padding(
                        padding: const EdgeInsetsDirectional.symmetric(horizontal: ThemeVars.paddingPage, vertical: 16),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(_buildingAndRoom(), style: const TextStyle(fontSize: 16,fontWeight: FontWeight.w400),),
                                const SizedBox(height: 2,),
                                Text("${_info["room"]["groupName"]}", style: const TextStyle(color: ThemeVars.colorTextTer, fontSize: 12),)
                              ],
                            ),
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                              decoration: const BoxDecoration(
                                borderRadius: BorderRadius.all(Radius.circular(10)),
                                color: ThemeVars.colorPrimaryLight,
                              ),
                              child: const Text("入住中", style: TextStyle(fontSize: 12),),
                            )
                          ],
                        ),
                      ),
                      const SolidDivider(),
                      SizedBox(
                        height: 50,
                        child: Row(
                          children: [
                            Expanded(
                              child: TextButton(
                                onPressed: () {
                                  Stacker.pushNamed(Keys.CHECK_IN_DETAIL_ELECTRICITY_USE_RECORD, arguments: { "roomId": _info?["roomId"]});
                                },
                                child: const Text("用电记录",),
                              ),
                            ),
                            const SolidDivider(direction: Axis.vertical,),
                            Expanded(
                              child: TextButton(
                                  onPressed: () {
                                    Stacker.pushNamed(Keys.CHECK_IN_DETAIL_LOCK_LIST, arguments: _info["roomId"]);
                                  },
                                  child: const Text("开门权限")
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              SliverPadding(
                padding: const EdgeInsets.only(top: 10),
                sliver: SliverOverlapAbsorber(
                    handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                    sliver: SliverAppBar(
                      pinned: true,
                      backgroundColor: Colors.white,
                      surfaceTintColor: Colors.white,
                      automaticallyImplyLeading: false,
                      forceElevated: innerBoxIsScrolled,
                      toolbarHeight: 0,
                      bottom: TabBar(
                        tabs: tabs.map((String name) => Tab(text: name)).toList(),
                        onTap: (index) {
                        },
                      ),
                    )
                ),
              )
            ];
          },
          body: CheckInInfoState(
            info: _info,
            mainRenter: _mainRenter,
            cohabitants: _cohabitants,
            changeInfo: _changeInfo,
            getCheckInInfo: _getCheckInInfo,
            child: TabBarView(
              children: [
                Detail(info: _info, mainRenter: _mainRenter,),
                Complete(),
                DueIn(checkInId: widget.checkInId),
              ],
            )
          ,)
        )
      ,)
    );
  }

}